package com.jxwifi.cloud.quickclean.order;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RidePath;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.idroid.utils.NoDoubleClickListener;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.app.AccountMgr;
import com.jxwifi.cloud.quickclean.app.ClientBasicActivity;
import com.jxwifi.cloud.quickclean.app.PasswordLogin;
import com.jxwifi.cloud.quickclean.bean.MyCleanersBean;
import com.jxwifi.cloud.quickclean.utils.TitleClient;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;
import com.view.SuperSwipeRefreshLayout;
import org.simple.eventbus.EventBus;
import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 我的保洁员
 * Created by Administrator on 2019/6/11.
 */

public class MyCleanerActivity extends ClientBasicActivity implements MyCleanerView,RouteSearch.OnRouteSearchListener {

    private String TAG = this.getClass().getSimpleName();
    @Bind(R.id.srl_my_cleaner_list)
    SuperSwipeRefreshLayout mSrlMyCleanerList;
    @Bind(R.id.rv_my_cleaner_list)
    RecyclerView mRvMyCleanerList;
    @Bind(R.id.searchView)
    SearchView searchView;  //搜索框
    @Bind(R.id.lin_search)
    LinearLayout lin_search;
    private int REDE_CONTACT = 205;

    private View notDataView;
    private int mPageIndex = 1;//页数
    private int mLimit = 20;

    //上个页面传入的值
    private String mOrderCode;
    private String mServiceTime;

    private MyCleanerPresenter mPresenter;
    public RouteSearch mRouteSearch;
    private boolean isCollection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_cleaner);
        ButterKnife.bind(this);
        openEventBus();
        mOrderCode = getIntent().getStringExtra("order_code");
        mServiceTime = getIntent().getStringExtra("service_time");
        isCollection = getIntent().getBooleanExtra("isCollection", false);
        //Log.i(TAG,"onCreate ==> isCollection = "+isCollection);
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);
        mPresenter = new MyCleanerPresenter(mBaseContext, this);
        initHead();
        initView();
    }

    private void initHead() {
        TitleClient holder = new TitleClient(ButterKnife.findById(this, R.id.lin_client_title));
        if (isCollection) {
            holder.defineTitle("选择收藏保洁员");
            lin_search.setVisibility(View.GONE);
        } else {
            holder.defineTitle("选择保洁员");
        }

        holder.defineLeft(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                onBackPressed();
            }
        });
    }

    public void initView() {
        mPresenter.onDataList(isCollection);
        mPresenter.Refresh(isCollection);
    }

    @Override
    public int getPage() {
        return mPageIndex;
    }

    @Override
    public int getLimit() {
        return mLimit;
    }

    @Override
    public String getOrderCode() {
        return mOrderCode;
    }

    @Override
    public String getServiceTime() {
        return mServiceTime;
    }

    @Override
    public RecyclerView getRView() {
        return mRvMyCleanerList;
    }

    @Override
    public SearchView getSeachView() {
        return searchView;
    }

    @Override
    public SuperSwipeRefreshLayout getSwip() {
        return mSrlMyCleanerList;
    }

    @Override
    public void onClickCleaning(MyCleanersBean mMyCleanersBean) {
        EventBus.getDefault().post(mMyCleanersBean, "e-mycleaner");
        finish();
    }

    @Override
    public RouteSearch getRouteSearch() {
        return mRouteSearch;
    }

    @Override
    public void jumpContacts() {
        //该Jar包CoordinatorLayout类与其他依赖包冲突
        /*RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.READ_CONTACTS).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean granted) throws Exception {
                if (granted) {
                    // 打开通讯录
                    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                    startActivityForResult(intent, REDE_CONTACT);
                }
            }
        });*/
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            //未获取到读取联系人权限
            //向系统申请权限
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS}, REDE_CONTACT);
        } else {
            // 打开通讯录
            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
            startActivityForResult(intent, REDE_CONTACT);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //判断用户是否，同意 获取联系人授权
        if (requestCode == REDE_CONTACT && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //获取到读取联系人权限
            // 打开通讯录
            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
            startActivityForResult(intent, REDE_CONTACT);
        } else {
            Toast.makeText(this, "未获取到联系人权限", Toast.LENGTH_SHORT).show();

        }
    }

    @Override
    public View getViews() {
        if (isCollection) {
            notDataView = getLayoutInflater().inflate(R.layout.qt_null_layout, (ViewGroup) mRvMyCleanerList.getParent(), false);
        } else {
            notDataView = getLayoutInflater().inflate(R.layout.null_layout, (ViewGroup) mRvMyCleanerList.getParent(), false);
            notDataView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPresenter.Refresh(isCollection);
                }
            });
        }

        return notDataView;
    }

    @Override
    public void onFailure(int errorCode, String msg) {
        Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
    }

    @Override
    public void onData() {
        PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
        if (PasswordLogin.mIsLogin) {
            if (isCollection) {
                mPresenter.getCollectionCleanerData();
            } else {
                mPresenter.getData();
            }

        }

    }

    int mrecordsPosition;

    //骑行路线规划结果
    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {
        if (i == 1000) {
            RidePath ridePath = rideRouteResult.getPaths().get(0);
            //setRideRoute(ridePath, rideRouteResult.getStartPos(), rideRouteResult.getTargetPos());
            float distance = ridePath.getDistance() / 1000;
            long duration = ridePath.getDuration() / 60;
            if (mPresenter.isSearch) {
                mPresenter.mrecordsFilter.get(mrecordsPosition).setRideDistance(distance);
                mPresenter.mrecordsFilter.get(mrecordsPosition).setRideDuration(duration);
                Log.i(TAG, "onRideRouteSearched ==> " + mrecordsPosition + " 距离/公里：" + distance + " 时间/分：" + duration + " getRideDistance = " + mPresenter.mrecordsFilter.get(mrecordsPosition).getRideDistance());
                mrecordsPosition++;
                mPresenter.setRideData(mrecordsPosition);
                if (mrecordsPosition == mPresenter.mrecordsFilter.size()) {
                    mrecordsPosition = 0;
                }
            } else {
                mPresenter.mrecords.get(mrecordsPosition).setRideDistance(distance);
                mPresenter.mrecords.get(mrecordsPosition).setRideDuration(duration);
                //Log.i(TAG,"onRideRouteSearched ==> "+mrecordsPosition+" 距离/公里：" + distance + " 时间/分：" + duration+" getRideDistance = "+mPresenter.mrecords.get(mrecordsPosition).getRideDistance());
                mrecordsPosition++;
                mPresenter.setRideData(mrecordsPosition);
                if (mrecordsPosition == mPresenter.mrecords.size()) {
                    mrecordsPosition = 0;
                }
            }


        } else {
            Log.i(TAG, "onRideRouteSearched: 路线规划失败");
        }
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {

    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REDE_CONTACT) {
            try {
                Uri uri = data.getData();
                ContentResolver cr = this.getContentResolver();
                Cursor cursor = cr.query(uri, null, null, null, null);
                //移动到游标到联系人表第一行
                if (cursor != null && cursor.moveToFirst()) {
                    //联系人姓名
                    String nameStr = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    //读取通讯录的号码
                    String phoneStr = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    cursor.close();
                    mPresenter.dialogshow.setContentText(phoneStr);
                } else {
                    new Throwable("数据库游标不存在");
                }
            } catch (Throwable throwable) {
                new Throwable("未知错误");
            }
        }
    }

/*    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(null != mPresenter.dialogshow){
                mPresenter.dialogshow.dismiss();
            }else{
                onBackPressed();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }*/
/*
    @Override
    public void onBackPressed() {
        if(null != mPresenter.dialogshow){
            mPresenter.dialogshow.dismiss();
        }else{
            onBackPressed();
        }
        super.onBackPressed();
    }*/
}